package array;

public class RotateImage48 {
    public void rotate(int[][] m) {
        if (m == null || m.length <= 1) {
            return;
        }

        for (int i = 0; i < m.length/2 ; i++) {
            for (int j = i; j < m.length - i - 1; j++) {
                rotateAt(m, i, j);
            }
        }
    }

    public void rotateAt(int[][] m, int i, int j) {
        int w = m.length;

        // 顺时针计算其他三个坐标
        // (x1, y1) + (x3, y3) = (w-1, w-1)
        // (x2, y2) + (x4, y4) = (w-1, w-1)

        int x1 = i;
        int y1 = j;

        int x2 = j;
        int y2 = w-i-1;

        int x3 = w-i-1;
        int y3 = w-j-1;

        int x4 = w-j-1;
        int y4 = i;

        int t1 = m[x1][y1];

        // 旋转
        m[x1][y1] = m[x4][y4];
        m[x4][y4] = m[x3][y3];
        m[x3][y3] = m[x2][y2];
        m[x2][y2] = t1;
    }
}
